#-------------------------------------------------------------------------------
# By Daoyu @2010-07-08
#-------------------------------------------------------------------------------

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from django.db.models import Q

from uncle.users.models import *
from uncle.project.models import *
from uncle.util.page import *
from uncle.util.util import *
from uncle.users.views import get_all_cat_skill_tool_tag


#-------------------------------------------------------------------------------
# Search the artist in the database. 
# Key word: means whole word search
#-------------------------------------------------------------------------------
@login_required
def search(request):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    ln, fn, role = '', '', ''
    artists, _artists = [x for x in User.objects.filter(Q(user_permissions__codename='is_artist'))], []
    
    if request.method == 'POST': # filter by key word
        fn = request.POST['fn_txt']
        fn = format_string(fn)

        keys = fn.split(' ')
        for key in keys:
            _artists, artists = append_non_repeat(_artists, artists,
                        [x for x in artists if x.first_name.lower().find(key) > -1])
            _artists, artists = append_non_repeat(_artists, artists,
                        [x for x in artists if x.last_name.lower().find(key) > -1])
            _artists, artists = append_non_repeat(_artists, artists,
                        [x for x in artists if x.get_profile().role.lower().find(key) > -1])
            _artists, artists = append_non_repeat(_artists, artists,
                        [x for x in artists if x.get_profile().language.lower().find(key) > -1])
            _artists, artists = append_non_repeat(_artists, artists,
                        [x for x in artists if x.get_profile().customer_skills.lower().find(key) > -1])
            
            sk_s = Skill.objects.all()
            for sk in sk_s:
                if sk.name.lower().find(key) > -1:                    
                    su = Skill_user.objects.filter(skill=sk)
                    if su:
                        _artists, artists = append_non_repeat(_artists, artists, [su[0].user])
            
            t_s = Tool.objects.all()
            for t in t_s:
                if t.name.lower().find(key) > -1:
                    tu = Tool_user.objects.filter(tool=t)
                    if tu:
                        _artists, artists = append_non_repeat(_artists, artists, [tu[0].user])

        _artists.sort(cmp=lambda x, y:cmp(x.last_name.lower(), y.last_name.lower()))
        __artists = split_into_pages(request, _artists)
    elif request.method == 'GET':
        __artists = None
#        artists.sort(cmp=lambda x, y:cmp(x.last_name.lower(), y.last_name.lower()))        
#        __artists = split_into_pages(request, artists)        
    
    ues = User_expire.objects.all()
    return render_to_response('user/search.html',
              {'artists':__artists, 'fn':fn, 'ln':ln, 'role':role, 'ues':ues },
              context_instance=RequestContext(request))

#-------------------------------------------------------------------------------
# Seach by given tags, skills, and tools.
# o_cat means the categories that are select with tools and skills
# old_cat means the categories with no tools and skills select.
#-------------------------------------------------------------------------------
@login_required
def search_by_category(request):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    current_cat, o_tool, o_skill, o_tag = None, [], [], []
    o_cat, old_cat = set([]), set([])
    skts = get_all_cat_skill_tool_tag()
    scroll = ''

    if request.GET.has_key('scroll'):
        scroll = request.GET['scroll']

    if request.GET.has_key('c'): # The now visiting category.
        temp = Category.objects.filter(id=request.GET['c'])
        if temp:
            current_cat = temp[0]

    artists, temp_art = User.objects.order_by('-auth_user.last_name').filter(Q(user_permissions__codename='is_artist')), []

    for x in range(0, 100):
        if request.GET.has_key('cat' + str(x)):
            old_cat.add(int(request.GET['cat' + str(x)]))
            tools = [z.id for z in Tool.objects.filter(category__id=request.GET['cat' + str(x)])]
            skills = [z.id for z in Skill.objects.filter(category__id=request.GET['cat' + str(x)])]
            temp1 = set([])
            for y in Tool_user.objects.all():
                if y.tool.id in tools:
                    temp1.add(y.user)
            for y in Skill_user.objects.all():
                if y.skill.id in skills:
                    temp1.add(y.user)
            temp_art.append(temp1)
        if request.GET.has_key('t' + str(x)):
            tool = Tool.objects.get(id=request.GET['t' + str(x)])
            o_tool.append(tool.id)
            o_cat.add(tool.category.id)
            temp_art.append([y.user for y in Tool_user.objects.filter(tool__id=tool.id)])

        if request.GET.has_key('s' + str(x)):
            skill = Skill.objects.get(id=request.GET['s' + str(x)])
            o_skill.append(skill.id)
            o_cat.add(skill.category.id)
            temp_art.append([y.user for y in Skill_user.objects.filter(skill__id=skill.id)])

        if request.GET.has_key('tag' + str(x)):
            tag = Tag.objects.get(id=request.GET['tag' + str(x)])
            o_tag.append(tag.id)
            o_cat.add(tag.category.id)
            temp_art.append([y.user for y in Tag_user.objects.filter(tag__id=tag.id)])

    if temp_art: # first get artists belong to each tags, and select the common artists.
        artists = [x for x in temp_art[0]]
        for x in temp_art[0]:
            for i in range(1, len(temp_art)):
                if x not in temp_art[i]:
                    artists.remove(x)
                    break
    _as = [x for x in artists]
    _as.sort(cmp=lambda x, y:cmp(x.last_name.lower(), y.last_name.lower()))
    _artists = split_into_pages(request, _as)
    ues = User_expire.objects.all()
    return render_to_response('user/search_by_category.html',
        {'skts':skts, 'category':current_cat, 'artists':_artists,
         'old_tools':o_tool, 'old_skills':o_skill, 'old_tags':o_tag,
         'old_cats':o_cat, 'old_categories':old_cat,
         'scroll':scroll, 'ues':ues, },
        context_instance=RequestContext(request))

@login_required
def moods(request):
    current_cat, o_tool, o_skill, o_tag = None, [], [], []
    o_cat, old_cat = set([]), set([])
    skts = get_all_cat_skill_tool_tag()
    scroll = ''

    if request.GET.has_key('scroll'):
        scroll = request.GET['scroll']

    if request.GET.has_key('c'): # The now visiting category.
        temp = Category.objects.filter(id=request.GET['c'])
        if temp:
            current_cat = temp[0]
    
    temp_bs = set([])
    
    for x in range(0, 100):
        if request.GET.has_key('cat' + str(x)):
            old_cat.add(int(request.GET['cat' + str(x)]))
            skills = [z.id for z in Skill.objects.filter(category__id=request.GET['cat' + str(x)])]
            for y in Skill_basket.objects.all():
                if y.skill.id in skills:
                    temp_bs.add(y.basket)

        if request.GET.has_key('s' + str(x)):
            skill = Skill.objects.get(id=request.GET['s' + str(x)])
            o_skill.append(skill.id)
            o_cat.add(skill.category.id)
            temp_bs.update([y.basket for y in Skill_basket.objects.filter(skill__id=skill.id)])
    
    _baskets = split_into_pages(request, list(temp_bs))
    
    return render_to_response('search/moods.html',
        {'skts':skts, 'category':current_cat, 'baskets':_baskets,
         'old_tools':o_tool, 'old_skills':o_skill, 'old_tags':o_tag,
         'old_cats':o_cat, 'old_categories':old_cat,
         'scroll':scroll, },
        context_instance=RequestContext(request))
    
#-------------------------------------------------------------------------------
# Search by alpha beta characters.
#-------------------------------------------------------------------------------
@login_required
def search_abc(request):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')

    abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    artists = User.objects.order_by('-auth_user.last_name').filter(Q(user_permissions__codename='is_artist'))
    key = ''
    if request.GET.has_key('key'): # filter by a ~ z
        key = request.GET['key']
        artists = artists.filter(last_name__istartswith=key)

    _as = [x for x in artists]
    _as.sort(cmp=lambda x, y:cmp(x.last_name.lower(), y.last_name.lower()))
    _artists = split_into_pages(request, _as)
    ues = User_expire.objects.all()
    return render_to_response('user/search_abc.html',
          {'artists':_artists, 'abc':list(abc), 'ues':ues,'key':key },
          context_instance=RequestContext(request))

def search_abc_asset(request):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    
    abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    assets = video.objects.order_by('title')
    if request.GET.has_key('key'): # filter by a ~ z
        assets = assets.filter(title__startswith=request.GET['key'])
        
    assets = split_into_pages(request, assets)
    from uncle.util.util import asset_avatar
    asset_avatar(assets.object_list)
    return render_to_response('user/search_abc_asset.html',
          {'assets':assets, 'abc':list(abc)},
          context_instance=RequestContext(request))

#-------------------------------------------------------------------------------
# Search by alpha beta characters in special skills.
#-------------------------------------------------------------------------------
@login_required
def search_specskill(request):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')

    abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    artists = User.objects.order_by('-auth_user.last_name').filter(Q(user_permissions__codename='is_artist'))
    if request.GET.has_key('key'): # filter by a ~ z
        artists = artists.filter(last_name__istartswith=request.GET['key'])
    
    _as = [x for x in artists]
    _as.sort(cmp=lambda x, y:cmp(x.last_name.lower(), y.last_name.lower()))
    _artists = split_into_pages(request, _as)
    ues = User_expire.objects.all()
    return render_to_response('user/search_specskill.html',
          {'artists':_artists, 'abc':list(abc), 'ues':ues, },
          context_instance=RequestContext(request))
    
#-------------------------------------------------------------------------------
# Search video by keywords.
#-------------------------------------------------------------------------------
@login_required
def search_video(request):
    
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    
    ln, fn, role = '', '', ''
    videos, _videos = [x for x in video.objects.all()], []
    
    if request.method == 'POST': # filter by key word
        fn = request.POST['fn_txt']
        fn = format_string(fn)

        keys = fn.split(' ')
        for key in keys:
            _videos, videos = append_non_repeat(_videos, videos,
                        [x for x in videos if x.title.lower().find(key) > -1])
            _videos, videos = append_non_repeat(_videos, videos,
                        [x for x in videos if x.text.lower().find(key) > -1]) 
            _videos, videos = append_non_repeat(_videos, videos,
                        [x for x in videos if x.user.username.lower().find(key) > -1])   
        _videos.sort(cmp=lambda x, y:cmp(x.title.lower(), y.title.lower()))
        _videos = split_into_pages(request, _videos)
        
        from uncle.util.util import asset_avatar
        asset_avatar(_videos.object_list)
        
    elif request.method == 'GET':
        _videos = None   
    
    return render_to_response('user/search_video.html',
          {'videos':_videos, },
          context_instance=RequestContext(request))

